package com.lx.chapter2.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * 类型转换工具类
 * @author 段誉
 * @create 2019-03-22 14:10
 */
public final class CastUtil {
  /**
   * 转为String型
   */
  public static String castString(Object obj) {
    return CastUtil.castString(obj, "");
  }

  /**
   * 转为String型(提供默认值)
   */
  public static String castString(Object obj, String defaultValue) {
    return obj == null ? defaultValue : String.valueOf(obj);
  }

  /**
   * 转为double型
   */
  public static double castDouble(Object obj) {
    return CastUtil.castDouble(obj, 0);
  }

  /**
   * 转为double型(提供默认值)
   */
  public static double castDouble(Object obj, double defaultValue) {
    double doubleValue = defaultValue;
    if (obj == null) {
      return defaultValue;
    }

    String strVaule = castString(obj);
    if (StringUtils.isEmpty(strVaule)) {
      return defaultValue;
    }

    try {
      doubleValue = Double.parseDouble(strVaule);
    } catch (NumberFormatException e) {
      return defaultValue;
    }
    return doubleValue;
  }

  /**
   * 转为long类型
   */
  public static long castLong(Object obj) {
    return CastUtil.castLong(obj, 0);
  }
  /**
   * 转为long类型(提供默认值)
   */
  public static long castLong(Object obj, long defaultValue) {
    long longValue = defaultValue;
    if (obj == null) {
      return defaultValue;
    }

    String strValue = castString(obj);
    if (StringUtils.isEmpty(strValue)) {
      return defaultValue;
    }

    try {
      longValue = Long.valueOf(strValue);
    } catch (NumberFormatException e) {
      return defaultValue;
    }
    return longValue;
  }

  /**
   * 转为int类型
   */
  public static int castInt(Object obj) {
    return CastUtil.castInt(obj, 0);
  }
  /**
   * 转为int类型(提供默认值)
   */
  public static int castInt(Object obj, int defaultValue) {
    int intValue = defaultValue;
    if (obj == null) {
      return defaultValue;
    }

    String strValue = String.valueOf(obj);
    if (StringUtils.isEmpty(strValue)) {
      return defaultValue;
    }

    try {
      intValue = Integer.valueOf(strValue);
    } catch (NumberFormatException e) {
      return defaultValue;
    }
    return intValue;
  }

  /**
   * 转为boolean类型
   */
  public static boolean castBoolean(Object obj) {
    return CastUtil.castBoolean(obj, false);
  }
  /**
   * 转为boolean类型(提供默认值)
   */
  public static boolean castBoolean(Object obj, boolean defaultValue) {
    boolean boolValue = defaultValue;
    if (obj == null) {
      return defaultValue;
    }
    boolValue = Boolean.parseBoolean(castString(obj));
    return boolValue;
  }


}
